import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Design, getPublicDesigns } from '../services/design';

const Gallery: React.FC = () => {
  const [selectedItem, setSelectedItem] = useState<Design | null>(null);
  const [designs, setDesigns] = useState<Design[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [roomTypeFilter, setRoomTypeFilter] = useState<string>('');
  const [designStyleFilter, setDesignStyleFilter] = useState<string>('');
  const limit = 12; // 每页显示12个设计

  // 获取公开设计数据
  const fetchPublicDesigns = async (page: number = 1, roomType?: string, designStyle?: string) => {
    try {
      setLoading(true);
      setError(null);
      const response = await getPublicDesigns({
        page,
        limit,
        roomType: roomType || undefined,
        designStyle: designStyle || undefined
      });
      
      if (response.success) {
        setDesigns(response.data.designs);
        setTotalPages(response.data.totalPages);
        setTotal(response.data.total);
        setCurrentPage(response.data.page);
      } else {
        setError('Failed to load designs');
      }
    } catch (err) {
      setError('Error loading designs');
      console.error('Error fetching public designs:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPublicDesigns(currentPage, roomTypeFilter, designStyleFilter);
  }, [currentPage, roomTypeFilter, designStyleFilter]);

  // 处理分页
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 处理筛选
  const handleFilterChange = (roomType: string, designStyle: string) => {
    setRoomTypeFilter(roomType);
    setDesignStyleFilter(designStyle);
    setCurrentPage(1); // 重置到第一页
  };

  // 格式化房间类型显示
  const formatRoomType = (roomType: string) => {
    const roomTypeMap: { [key: string]: string } = {
      living: 'Living Room',
      bedroom: 'Bedroom',
      kitchen: 'Kitchen',
      bathroom: 'Bathroom',
      office: 'Office',
      dining: 'Dining Room'
    };
    return roomTypeMap[roomType] || roomType;
  };

  // 格式化设计风格显示
  const formatDesignStyle = (style: string) => {
    const styleMap: { [key: string]: string } = {
      modern: 'Modern',
      traditional: 'Traditional',
      scandinavian: 'Scandinavian',
      industrial: 'Industrial',
      bohemian: 'Bohemian',
      minimalist: 'Minimalist'
    };
    return styleMap[style] || style;
  };

  // 渲染分页组件
  const renderPagination = () => {
    if (totalPages <= 1) return null;

    const pages = [];
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 上一页按钮
    if (currentPage > 1) {
      pages.push(
        <button
          key="prev"
          onClick={() => handlePageChange(currentPage - 1)}
          className="px-3 py-2 mx-1 text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
        >
          Previous
        </button>
      );
    }

    // 页码按钮
    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          onClick={() => handlePageChange(i)}
          className={`px-3 py-2 mx-1 border rounded-md ${
            i === currentPage
              ? 'bg-blue-500 text-white border-blue-500'
              : 'text-gray-500 bg-white border-gray-300 hover:bg-gray-50'
          }`}
        >
          {i}
        </button>
      );
    }

    // 下一页按钮
    if (currentPage < totalPages) {
      pages.push(
        <button
          key="next"
          onClick={() => handlePageChange(currentPage + 1)}
          className="px-3 py-2 mx-1 text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
        >
          Next
        </button>
      );
    }

    return (
      <div className="flex justify-center items-center mt-8">
        {pages}
      </div>
    );
  };

  // 渲染筛选器
  const renderFilters = () => {
    const roomTypes = ['', 'living', 'bedroom', 'kitchen', 'bathroom', 'office', 'dining'];
    const designStyles = ['', 'modern', 'traditional', 'scandinavian', 'industrial', 'bohemian', 'minimalist'];

    return (
      <div className="flex flex-wrap gap-4 mb-8 justify-center">
        <select
          value={roomTypeFilter}
          onChange={(e) => handleFilterChange(e.target.value, designStyleFilter)}
          className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="">All Room Types</option>
          {roomTypes.slice(1).map(type => (
            <option key={type} value={type}>{formatRoomType(type)}</option>
          ))}
        </select>
        
        <select
          value={designStyleFilter}
          onChange={(e) => handleFilterChange(roomTypeFilter, e.target.value)}
          className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="">All Design Styles</option>
          {designStyles.slice(1).map(style => (
            <option key={style} value={style}>{formatDesignStyle(style)}</option>
          ))}
        </select>
      </div>
    );
  };

  return (
    <div className="py-20 bg-gradient-to-b from-gray-50 to-gray-100">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-16">
          <motion.h1
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
            className="text-4xl font-bold text-gray-900"
          >
            AI Design Gallery
          </motion.h1>
          <motion.p
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.2 }}
            className="mt-4 text-xl text-gray-600"
          >
            Explore our collection of AI-generated room designs
          </motion.p>
          {total > 0 && (
            <motion.p
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.4 }}
              className="mt-2 text-sm text-gray-500"
            >
              {total} designs available
            </motion.p>
          )}
        </div>

        {/* 筛选器 */}
        {renderFilters()}

        {/* 加载状态 */}
        {loading && (
          <div className="flex justify-center items-center py-20">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
          </div>
        )}

        {/* 错误状态 */}
        {error && (
          <div className="text-center py-20">
            <div className="text-red-500 text-lg mb-4">{error}</div>
            <button
              onClick={() => fetchPublicDesigns(currentPage, roomTypeFilter, designStyleFilter)}
              className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
            >
              Retry
            </button>
          </div>
        )}

        {/* 设计网格 */}
        {!loading && !error && (
          <>
            {designs.length === 0 ? (
              <div className="text-center py-20">
                <div className="text-gray-500 text-lg">No designs found</div>
                <p className="text-gray-400 mt-2">Try adjusting your filters or check back later</p>
              </div>
            ) : (
              <div className="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 sm:gap-8">
                {designs.map((design, index) => (
                  <motion.div
                    key={design.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: index * 0.1 }}
                    className="bg-white rounded-xl shadow-md overflow-hidden cursor-pointer transform transition-transform hover:scale-105"
                    onClick={() => setSelectedItem(design)}
                  >
                    <div className="h-48 sm:h-64 overflow-hidden">
                      <img
                        src={design.generatedImageUrl || design.originalImageUrl}
                        alt={`${design.designStyle ? formatDesignStyle(design.designStyle) : 'Unknown Style'} ${design.roomType ? formatRoomType(design.roomType) : 'Unknown Room'}`}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement;
                          target.src = design.originalImageUrl;
                        }}
                      />
                    </div>
                    <div className="p-3 sm:p-6 hidden sm:block">
                      <h3 className="text-lg font-semibold text-gray-900">
                        {design.designStyle ? formatDesignStyle(design.designStyle) : 'Unknown Style'} {design.roomType ? formatRoomType(design.roomType) : 'Unknown Room'}
                      </h3>
                      <div className="mt-2 flex space-x-2">
                        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                          {design.designStyle ? formatDesignStyle(design.designStyle) : 'Unknown Style'}
                        </span>
                        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                          {design.roomType ? formatRoomType(design.roomType) : 'Unknown Room'}
                        </span>
                      </div>
                    </div>
                  </motion.div>
                ))}
              </div>
            )}
            
            {/* 分页 */}
            {renderPagination()}
          </>
        )}
      </div>

      {/* Modal for detailed view */}
      {selectedItem && (
        <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-4xl w-full max-h-[90vh] overflow-auto">
            <div className="relative">
              <button
                onClick={() => setSelectedItem(null)}
                className="absolute top-4 right-4 bg-white rounded-full p-2 shadow-md z-10"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
              <img
                src={selectedItem.generatedImageUrl || selectedItem.originalImageUrl}
                alt={`${selectedItem.designStyle ? formatDesignStyle(selectedItem.designStyle) : 'Unknown Style'} ${selectedItem.roomType ? formatRoomType(selectedItem.roomType) : 'Unknown Room'}`}
                className="w-full h-[50vh] object-cover"
                onError={(e) => {
                  const target = e.target as HTMLImageElement;
                  target.src = selectedItem.originalImageUrl;
                }}
              />
            </div>
            <div className="p-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-4">
                {selectedItem.designStyle ? formatDesignStyle(selectedItem.designStyle) : 'Unknown Style'} {selectedItem.roomType ? formatRoomType(selectedItem.roomType) : 'Unknown Room'}
              </h2>
              <div className="flex flex-wrap gap-2 mb-6">
                <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                  Style: {selectedItem.designStyle ? formatDesignStyle(selectedItem.designStyle) : 'Unknown Style'}
                </span>
                <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                  Room: {selectedItem.roomType ? formatRoomType(selectedItem.roomType) : 'Unknown Room'}
                </span>
                <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${
                  selectedItem.status === 'completed' ? 'bg-green-100 text-green-800' :
                  selectedItem.status === 'processing' ? 'bg-yellow-100 text-yellow-800' :
                  selectedItem.status === 'failed' ? 'bg-red-100 text-red-800' :
                  'bg-gray-100 text-gray-800'
                }`}>
                  Status: {selectedItem.status.charAt(0).toUpperCase() + selectedItem.status.slice(1)}
                </span>
                {selectedItem.creditsUsed > 0 && (
                  <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-purple-100 text-purple-800">
                    Credits: {selectedItem.creditsUsed}
                  </span>
                )}
              </div>
              
              {selectedItem.prompt && (
                <div className="mb-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">Design Prompt</h3>
                  <p className="text-gray-700 bg-gray-50 p-4 rounded-lg">{selectedItem.prompt}</p>
                </div>
              )}
              
              <div className="border-t border-gray-200 pt-6">
                <h3 className="text-lg font-semibold text-gray-900 mb-4">Design Information</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
                  <div>
                    <span className="font-medium">Design ID:</span> {selectedItem.id}
                  </div>
                  <div>
                    <span className="font-medium">Created:</span> {new Date(selectedItem.createdAt).toLocaleDateString()}
                  </div>
                  {selectedItem.updatedAt !== selectedItem.createdAt && (
                    <div>
                      <span className="font-medium">Updated:</span> {new Date(selectedItem.updatedAt).toLocaleDateString()}
                    </div>
                  )}
                  {selectedItem.errorMessage && (
                    <div className="md:col-span-2">
                      <span className="font-medium text-red-600">Error:</span> 
                      <span className="text-red-600">{selectedItem.errorMessage}</span>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Gallery;
